import 'package:flutter_wan_android/core/storage/kv_cache_storage.dart';
import 'package:flutter_wan_android/core/utils/json_util.dart';
import 'package:flutter_wan_android/data/user/user_entity.dart';
import 'package:flutter_wan_android/data/user/user_table_struct.dart';
import 'package:sqflite/sqflite.dart';

import '../../core/storage/database_storage.dart';

/// 本地数据存储api
class UserLocalApi {
  static const String _keyLoginState = "key_login_state";

  final DataBaseStorage _dbStorage;
  final KVCacheStorage _kvStorage;

  UserLocalApi(this._dbStorage,this._kvStorage);

  Future<void> loginSuccess(UserEntity user) async{
    await _kvStorage.setBool(_keyLoginState, true);
    insert(user);
  }

  Future<bool> getLoginState() async{
    return await _kvStorage.getBool(_keyLoginState);
  }

  Future<void> logout() async{
    await _kvStorage.setBool(_keyLoginState, false);
  }


  Future<int> insert(UserEntity user) async {
    // _useSqlInsert(user);
    final db = await _dbStorage.database;
    return db.insert(
      UserTableStruct.tableName,
      user.toDb(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  /// 案例 使用sql语句插入数据
  void _useSqlInsert(UserEntity user) async {
    final db = await _dbStorage.database;
    await db.rawInsert(
      '''
    INSERT INTO ${UserTableStruct.tableName} (
      ${UserTableStruct.colId},
      ${UserTableStruct.colAdmin},
      ${UserTableStruct.colChapterTops},
      ${UserTableStruct.colCoinCount},
      ${UserTableStruct.colCollectIds},
      ${UserTableStruct.colEmail},
      ${UserTableStruct.colIcon},
      ${UserTableStruct.colNickname},
      ${UserTableStruct.colPassword},
      ${UserTableStruct.colPublicName},
      ${UserTableStruct.colToken},
      ${UserTableStruct.colUsername}
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  ''',
      [
        user.id,
        user.admin ? 1 : 0,
        JsonUtil.encodeJson(user.chapterTops),
        user.coinCount,
        JsonUtil.encodeJson(user.collectIds),
        user.email,
        user.icon,
        user.nickname,
        user.password,
        user.publicName,
        user.token,
        user.username,
      ],
    );
  }

  Future<int> update(UserEntity user) async {
    final db = await _dbStorage.database;
    return db.update(UserTableStruct.tableName, user.toDb(),
        where: "&{UserTableStruct.colId} = ?",
        whereArgs: [user.id]);
  }

  Future<int> delete(int id) async {
    final db = await _dbStorage.database;
    return await db.delete(
      UserTableStruct.tableName,
      where: '${UserTableStruct.colId} = ?',
      whereArgs: [id],
    );
  }

  Future<UserEntity?> getOne(int id) async {
    final db = await _dbStorage.database;
    final result = await db.query(
      UserTableStruct.tableName,
      where: '${UserTableStruct.colId} = ?',
      whereArgs: [id],
      limit: 1,
    );
    if (result.isNotEmpty) {
      return UserEntity.fromDb(result.first);
    }
    return null;
  }

  Future<List<UserEntity>> getAll() async {
    final db = await _dbStorage.database;
    final result = await db.query(UserTableStruct.tableName);
    return result.map((e) => UserEntity.fromDb(e)).toList();
  }
}
